<?php
require_once 'FShell/BaseShell.php';

abstract class BaseCycleShell extends BaseShell {
	protected $cycleRunTimes = 10000; //0 means unlimited
	protected $cycleSleepSeconds = 3; //0 means unlimited
	
	protected $cycleRunCount = 0;
	
	public function setCycle($cycleRunTimes = 10000, $cycleSleepSeconds = 3) {
		if ($cycleRunTimes < 0 || $cycleSleepSeconds < 0) throw new ShellExceptioin('cycleRunTimes or cycleSleepSeconds should not be less than zero');
		if ($cycleRunTimes == 0 && $cycleSleepSeconds == 0) throw new ShellExceptioin('cycleRunTimes and cycleSleepSeconds should not be unlimited at the same time');
		
		$this->cycleRunTimes = $cycleRunTimes;
		$this->cycleSleepSeconds = $cycleSleepSeconds;
		
		return $this;
	}
	
	public function execute() {
		$this->beforeRun();
		
		if ($this->cycleRunTimes > 0) {
			for ($i = 0; $i < $this->cycleRunTimes; $i++) {
				$this->cycleRunCount++;
				if ($this->isNeedSleep($this->run())) $this->sleep();
			}
		} elseif ($this->cycleRunTimes == 0) {
			while (1) {
				$this->cycleRunCount++;
				if ($this->isNeedSleep($this->run())) $this->sleep();
			}
		}
		
		$this->afterRun();
	}
	
	protected function run() {
		throw new ShellException("you should rewrite me in the subclass");
	}
	
	abstract protected function isNeedSleep($runResult = null);
	
	protected function sleep() {
		if (!$this->cycleSleepSeconds) return ;
		sleep($this->cycleSleepSeconds);
	}
}
